<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>备份管理 - 个人云笔记</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/lucide@latest/dist/umd/lucide.js">
    <script src="https://cdn.jsdelivr.net/npm/lucide@latest/dist/umd/lucide.js"></script>
</head>
<body class="bg-gray-50 min-h-screen">
    <!-- 导航栏 -->
    <nav class="bg-white shadow-sm border-b">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between h-16">
                <div class="flex items-center">
                    <h1 class="text-xl font-semibold text-gray-900">备份管理</h1>
                </div>
                <div class="flex items-center space-x-4">
                    <button onclick="goBack()" class="text-gray-600 hover:text-gray-900">
                        <i data-lucide="arrow-left" class="w-5 h-5"></i>
                        返回
                    </button>
                </div>
            </div>
        </div>
    </nav>

    <div class="max-w-7xl mx-auto py-6 px-4 sm:px-6 lg:px-8">
        <!-- 统计卡片 -->
        <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
            <div class="bg-white rounded-lg shadow p-6">
                <div class="flex items-center">
                    <div class="flex-shrink-0">
                        <i data-lucide="database" class="w-8 h-8 text-blue-600"></i>
                    </div>
                    <div class="ml-4">
                        <p class="text-sm font-medium text-gray-500">总备份数</p>
                        <p class="text-2xl font-semibold text-gray-900" id="totalBackups">-</p>
                    </div>
                </div>
            </div>

            <div class="bg-white rounded-lg shadow p-6">
                <div class="flex items-center">
                    <div class="flex-shrink-0">
                        <i data-lucide="hard-drive" class="w-8 h-8 text-green-600"></i>
                    </div>
                    <div class="ml-4">
                        <p class="text-sm font-medium text-gray-500">总大小</p>
                        <p class="text-2xl font-semibold text-gray-900" id="totalSize">-</p>
                    </div>
                </div>
            </div>

            <div class="bg-white rounded-lg shadow p-6">
                <div class="flex items-center">
                    <div class="flex-shrink-0">
                        <i data-lucide="calendar" class="w-8 h-8 text-purple-600"></i>
                    </div>
                    <div class="ml-4">
                        <p class="text-sm font-medium text-gray-500">最新备份</p>
                        <p class="text-sm font-semibold text-gray-900" id="newestBackup">-</p>
                    </div>
                </div>
            </div>

            <div class="bg-white rounded-lg shadow p-6">
                <div class="flex items-center">
                    <div class="flex-shrink-0">
                        <i data-lucide="activity" class="w-8 h-8 text-orange-600"></i>
                    </div>
                    <div class="ml-4">
                        <p class="text-sm font-medium text-gray-500">调度状态</p>
                        <p class="text-sm font-semibold text-gray-900" id="schedulerStatus">-</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- 操作按钮 -->
        <div class="bg-white rounded-lg shadow mb-8">
            <div class="px-6 py-4 border-b border-gray-200">
                <h2 class="text-lg font-medium text-gray-900">备份操作</h2>
            </div>
            <div class="p-6">
                <div class="flex flex-wrap gap-4">
                    <button onclick="createBackup()" 
                            class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                        <i data-lucide="plus" class="w-4 h-4 mr-2"></i>
                        创建备份
                    </button>
                    
                    <button onclick="createSchemaBackup()" 
                            class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500">
                        <i data-lucide="database" class="w-4 h-4 mr-2"></i>
                        创建结构备份
                    </button>
                    
                    <button onclick="cleanupBackups()" 
                            class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-red-600 hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500">
                        <i data-lucide="trash-2" class="w-4 h-4 mr-2"></i>
                        清理过期备份
                    </button>
                    
                    <button onclick="showRestoreHistory()" 
                            class="inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                        <i data-lucide="history" class="w-4 h-4 mr-2"></i>
                        恢复历史
                    </button>
                    
                    <button onclick="refreshData()" 
                            class="inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                        <i data-lucide="refresh-cw" class="w-4 h-4 mr-2"></i>
                        刷新
                    </button>
                </div>
            </div>
        </div>

        <!-- 备份列表 -->
        <div class="bg-white rounded-lg shadow">
            <div class="px-6 py-4 border-b border-gray-200">
                <h2 class="text-lg font-medium text-gray-900">备份文件列表</h2>
            </div>
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                文件名
                            </th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                大小
                            </th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                创建时间
                            </th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                状态
                            </th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                操作
                            </th>
                        </tr>
                    </thead>
                    <tbody id="backupList" class="bg-white divide-y divide-gray-200">
                        <!-- 备份列表将在这里动态生成 -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- 加载提示 -->
    <div id="loadingModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 hidden items-center justify-center z-50">
        <div class="bg-white rounded-lg p-6 max-w-sm mx-auto">
            <div class="flex items-center">
                <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-900" id="loadingText">处理中...</p>
                </div>
            </div>
        </div>
    </div>

    <!-- 通知组件 -->
    <div id="notification" class="fixed top-4 right-4 z-50 hidden">
        <div class="bg-white rounded-lg shadow-lg border border-gray-200 p-4 max-w-sm">
            <div class="flex items-start">
                <div class="flex-shrink-0">
                    <i id="notificationIcon" class="w-5 h-5"></i>
                </div>
                <div class="ml-3">
                    <p id="notificationMessage" class="text-sm font-medium text-gray-900"></p>
                </div>
                <div class="ml-auto pl-3">
                    <button onclick="hideNotification()" class="text-gray-400 hover:text-gray-600">
                        <i data-lucide="x" class="w-4 h-4"></i>
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 全局变量
        let backups = [];
        let stats = {};

        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            lucide.createIcons();
            loadData();
        });

        // 加载所有数据
        async function loadData() {
            await Promise.all([
                loadBackupStats(),
                loadBackupList(),
                loadSchedulerStatus()
            ]);
        }

        // 加载备份统计
        async function loadBackupStats() {
            try {
                const response = await fetch('/api/backup/stats', {
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`
                    }
                });

                if (response.ok) {
                    const result = await response.json();
                    stats = result.data;
                    updateStatsDisplay();
                }
            } catch (error) {
                console.error('Failed to load backup stats:', error);
            }
        }

        // 加载备份列表
        async function loadBackupList() {
            try {
                const response = await fetch('/api/backup/list', {
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`
                    }
                });

                if (response.ok) {
                    const result = await response.json();
                    backups = result.data.backups;
                    updateBackupList();
                }
            } catch (error) {
                console.error('Failed to load backup list:', error);
            }
        }

        // 加载调度器状态
        async function loadSchedulerStatus() {
            try {
                const response = await fetch('/api/backup/scheduler/status', {
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`
                    }
                });

                if (response.ok) {
                    const result = await response.json();
                    updateSchedulerStatus(result.data.tasks);
                }
            } catch (error) {
                console.error('Failed to load scheduler status:', error);
            }
        }

        // 更新统计显示
        function updateStatsDisplay() {
            document.getElementById('totalBackups').textContent = stats.totalBackups || 0;
            document.getElementById('totalSize').textContent = stats.formattedTotalSize || '0 B';
            
            const newestBackup = stats.newestBackup ? 
                new Date(stats.newestBackup).toLocaleDateString('zh-CN') : '无';
            document.getElementById('newestBackup').textContent = newestBackup;
        }

        // 更新调度器状态
        function updateSchedulerStatus(tasks) {
            const backupTask = tasks['database-backup'];
            const status = backupTask && backupTask.running ? '运行中' : '已停止';
            document.getElementById('schedulerStatus').textContent = status;
        }

        // 更新备份列表
        function updateBackupList() {
            const tbody = document.getElementById('backupList');
            
            if (backups.length === 0) {
                tbody.innerHTML = `
                    <tr>
                        <td colspan="5" class="px-6 py-4 text-center text-gray-500">
                            暂无备份文件
                        </td>
                    </tr>
                `;
                return;
            }

            tbody.innerHTML = backups.map(backup => `
                <tr>
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                        ${backup.fileName}
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                        ${backup.formattedSize}
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                        ${new Date(backup.createdAt).toLocaleString('zh-CN')}
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                            正常
                        </span>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                        <button onclick="verifyBackup('${backup.fileName}')" 
                                class="text-blue-600 hover:text-blue-900 mr-3">
                            验证
                        </button>
                        <button onclick="restoreFromBackup('${backup.fileName}')" 
                                class="text-orange-600 hover:text-orange-900 mr-3">
                            恢复
                        </button>
                        <button onclick="downloadBackup('${backup.fileName}')" 
                                class="text-green-600 hover:text-green-900">
                            下载
                        </button>
                    </td>
                </tr>
            `).join('');
        }

        // 创建备份
        async function createBackup() {
            showLoading('正在创建备份...');
            
            try {
                const response = await fetch('/api/backup/create', {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`
                    }
                });

                const result = await response.json();
                
                if (result.success) {
                    showNotification('备份创建成功', 'success');
                    await loadData();
                } else {
                    showNotification(result.message || '备份创建失败', 'error');
                }
            } catch (error) {
                showNotification('备份创建失败', 'error');
            } finally {
                hideLoading();
            }
        }

        // 清理过期备份
        async function cleanupBackups() {
            if (!confirm('确定要清理过期备份吗？此操作不可撤销。')) {
                return;
            }

            showLoading('正在清理过期备份...');
            
            try {
                const response = await fetch('/api/backup/cleanup', {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`
                    }
                });

                const result = await response.json();
                
                if (result.success) {
                    const message = `清理完成，删除了 ${result.data.deletedCount} 个备份文件，释放了 ${result.data.formattedDeletedSize} 空间`;
                    showNotification(message, 'success');
                    await loadData();
                } else {
                    showNotification(result.message || '清理失败', 'error');
                }
            } catch (error) {
                showNotification('清理失败', 'error');
            } finally {
                hideLoading();
            }
        }

        // 验证备份
        async function verifyBackup(fileName) {
            showLoading('正在验证备份...');
            
            try {
                const response = await fetch('/api/backup/verify', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${localStorage.getItem('token')}`
                    },
                    body: JSON.stringify({ fileName })
                });

                const result = await response.json();
                
                if (result.success) {
                    const message = result.data.valid ? '备份文件验证通过' : `备份文件验证失败: ${result.data.error}`;
                    const type = result.data.valid ? 'success' : 'error';
                    showNotification(message, type);
                } else {
                    showNotification(result.message || '验证失败', 'error');
                }
            } catch (error) {
                showNotification('验证失败', 'error');
            } finally {
                hideLoading();
            }
        }

        // 下载备份
        function downloadBackup(fileName) {
            const token = localStorage.getItem('token');
            const url = `/api/backup/download/${fileName}`;
            
            // 创建一个临时的a标签来触发下载
            const a = document.createElement('a');
            a.href = url;
            a.download = fileName;
            a.style.display = 'none';
            
            // 添加Authorization头部（通过创建一个新的请求）
            fetch(url, {
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            }).then(response => {
                if (response.ok) {
                    return response.blob();
                } else {
                    throw new Error('下载失败');
                }
            }).then(blob => {
                const url = window.URL.createObjectURL(blob);
                a.href = url;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                window.URL.revokeObjectURL(url);
                showNotification('下载开始', 'success');
            }).catch(error => {
                showNotification('下载失败', 'error');
            });
        }

        // 刷新数据
        async function refreshData() {
            showLoading('正在刷新数据...');
            await loadData();
            hideLoading();
            showNotification('数据已刷新', 'success');
        }

        // 返回上一页
        function goBack() {
            window.history.back();
        }

        // 显示加载提示
        function showLoading(text = '处理中...') {
            document.getElementById('loadingText').textContent = text;
            document.getElementById('loadingModal').classList.remove('hidden');
            document.getElementById('loadingModal').classList.add('flex');
        }

        // 隐藏加载提示
        function hideLoading() {
            document.getElementById('loadingModal').classList.add('hidden');
            document.getElementById('loadingModal').classList.remove('flex');
        }

        // 显示通知
        function showNotification(message, type = 'info') {
            const notification = document.getElementById('notification');
            const icon = document.getElementById('notificationIcon');
            const messageEl = document.getElementById('notificationMessage');

            messageEl.textContent = message;

            // 设置图标和颜色
            icon.className = 'w-5 h-5';
            if (type === 'success') {
                icon.setAttribute('data-lucide', 'check-circle');
                icon.classList.add('text-green-600');
            } else if (type === 'error') {
                icon.setAttribute('data-lucide', 'alert-circle');
                icon.classList.add('text-red-600');
            } else {
                icon.setAttribute('data-lucide', 'info');
                icon.classList.add('text-blue-600');
            }

            lucide.createIcons();
            notification.classList.remove('hidden');

            // 3秒后自动隐藏
            setTimeout(hideNotification, 3000);
        }

        // 创建结构备份
        async function createSchemaBackup() {
            showLoading('正在创建结构备份...');
            
            try {
                const response = await fetch('/api/backup/schema', {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`
                    }
                });

                const result = await response.json();
                
                if (result.success) {
                    showNotification('结构备份创建成功', 'success');
                    await loadData();
                } else {
                    showNotification(result.message || '结构备份创建失败', 'error');
                }
            } catch (error) {
                showNotification('结构备份创建失败', 'error');
            } finally {
                hideLoading();
            }
        }

        // 从备份恢复
        async function restoreFromBackup(fileName) {
            // 显示确认对话框
            const confirmed = await showRestoreConfirmDialog(fileName);
            if (!confirmed) {
                return;
            }

            showLoading('正在恢复数据库...');
            
            try {
                const response = await fetch('/api/backup/restore', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${localStorage.getItem('token')}`
                    },
                    body: JSON.stringify({ 
                        fileName: fileName,
                        createPreRestoreBackup: true,
                        confirmRestore: 'true'
                    })
                });

                const result = await response.json();
                
                if (result.success) {
                    let message = '数据库恢复成功';
                    if (result.data.preRestoreBackup) {
                        message += `，已创建恢复前备份：${result.data.preRestoreBackup}`;
                    }
                    showNotification(message, 'success');
                    await loadData();
                } else {
                    showNotification(result.message || '数据库恢复失败', 'error');
                }
            } catch (error) {
                showNotification('数据库恢复失败', 'error');
            } finally {
                hideLoading();
            }
        }

        // 显示恢复确认对话框
        function showRestoreConfirmDialog(fileName) {
            return new Promise((resolve) => {
                const modal = document.createElement('div');
                modal.className = 'fixed inset-0 bg-gray-600 bg-opacity-50 flex items-center justify-center z-50';
                modal.innerHTML = `
                    <div class="bg-white rounded-lg p-6 max-w-md mx-auto">
                        <div class="flex items-center mb-4">
                            <i data-lucide="alert-triangle" class="w-8 h-8 text-orange-600 mr-3"></i>
                            <h3 class="text-lg font-medium text-gray-900">确认数据库恢复</h3>
                        </div>
                        <div class="mb-4">
                            <p class="text-sm text-gray-600 mb-2">您即将从以下备份文件恢复数据库：</p>
                            <p class="text-sm font-medium text-gray-900 bg-gray-100 p-2 rounded">${fileName}</p>
                            <div class="mt-3 text-sm text-red-600">
                                <p>⚠️ 警告：</p>
                                <ul class="list-disc list-inside mt-1 space-y-1">
                                    <li>此操作将替换所有当前数据</li>
                                    <li>系统将自动创建恢复前备份</li>
                                    <li>此操作不可轻易撤销</li>
                                </ul>
                            </div>
                        </div>
                        <div class="flex justify-end space-x-3">
                            <button onclick="this.closest('.fixed').remove(); resolve(false)" 
                                    class="px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
                                取消
                            </button>
                            <button onclick="this.closest('.fixed').remove(); resolve(true)" 
                                    class="px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-red-600 hover:bg-red-700">
                                确认恢复
                            </button>
                        </div>
                    </div>
                `;
                
                // 添加事件监听器
                const buttons = modal.querySelectorAll('button');
                buttons[0].onclick = () => { modal.remove(); resolve(false); };
                buttons[1].onclick = () => { modal.remove(); resolve(true); };
                
                document.body.appendChild(modal);
                lucide.createIcons();
            });
        }

        // 显示恢复历史
        async function showRestoreHistory() {
            showLoading('正在加载恢复历史...');
            
            try {
                const response = await fetch('/api/backup/restore/history', {
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`
                    }
                });

                const result = await response.json();
                
                if (result.success) {
                    showRestoreHistoryModal(result.data.history);
                } else {
                    showNotification(result.message || '加载恢复历史失败', 'error');
                }
            } catch (error) {
                showNotification('加载恢复历史失败', 'error');
            } finally {
                hideLoading();
            }
        }

        // 显示恢复历史模态框
        function showRestoreHistoryModal(history) {
            const modal = document.createElement('div');
            modal.className = 'fixed inset-0 bg-gray-600 bg-opacity-50 flex items-center justify-center z-50';
            
            const historyRows = history.length > 0 ? history.map(item => `
                <tr>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                        ${new Date(item.timestamp).toLocaleString('zh-CN')}
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                        ${item.backupFileName || 'N/A'}
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm">
                        ${item.success ? 
                            '<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">成功</span>' : 
                            '<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800">失败</span>'
                        }
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                        ${item.preRestoreBackup || '-'}
                    </td>
                </tr>
            `).join('') : `
                <tr>
                    <td colspan="4" class="px-6 py-4 text-center text-gray-500">
                        暂无恢复历史记录
                    </td>
                </tr>
            `;

            modal.innerHTML = `
                <div class="bg-white rounded-lg max-w-4xl w-full mx-4 max-h-[80vh] overflow-hidden">
                    <div class="px-6 py-4 border-b border-gray-200 flex justify-between items-center">
                        <h3 class="text-lg font-medium text-gray-900">恢复历史</h3>
                        <button onclick="this.closest('.fixed').remove()" class="text-gray-400 hover:text-gray-600">
                            <i data-lucide="x" class="w-5 h-5"></i>
                        </button>
                    </div>
                    <div class="overflow-y-auto max-h-[60vh]">
                        <table class="min-w-full divide-y divide-gray-200">
                            <thead class="bg-gray-50">
                                <tr>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                        恢复时间
                                    </th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                        备份文件
                                    </th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                        状态
                                    </th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                        恢复前备份
                                    </th>
                                </tr>
                            </thead>
                            <tbody class="bg-white divide-y divide-gray-200">
                                ${historyRows}
                            </tbody>
                        </table>
                    </div>
                    <div class="px-6 py-4 border-t border-gray-200 flex justify-end">
                        <button onclick="this.closest('.fixed').remove()" 
                                class="px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
                            关闭
                        </button>
                    </div>
                </div>
            `;
            
            document.body.appendChild(modal);
            lucide.createIcons();
        }

        // 隐藏通知
        function hideNotification() {
            document.getElementById('notification').classList.add('hidden');
        }
    </script>
</body>
</html>